package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.*;
import org.example.models.R;
import org.example.service.EmployeeService;
import org.example.service.SalaryPaymentRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.*;

@RestController
@RequestMapping("/outsize")
public class SalaryPaymentRecordsController {
    @Autowired
    SalaryPaymentRecordsService salaryPaymentRecordsService;
    @Autowired
    EmployeeService employeeService;
    @GetMapping()
    public R<Page<SalaryPaymentRecords>> page(
            @RequestParam(name="current",defaultValue = "1") int current,
            @RequestParam(name="size",defaultValue = "10") int size,
            // 新增年份和月份参数（非必填）
            @RequestParam(name="year",required = false) Integer year,
            @RequestParam(name="month",required = false) Integer month,
            @RequestAttribute("username") String username
            ) {
        QueryWrapper<SalaryPaymentRecords> queryWrapper = new QueryWrapper<>();

        // 原有条件
        // 新增：年份查询条件
        if(year != null) {
            // 使用SQL的DATE_FORMAT函数提取年份（适用于MySQL）
            queryWrapper.apply("DATE_FORMAT(release_date, '%Y') = {0}", year);
        }

        // 处理Date类型的月份查询（重点修改部分）
        if(month != null && month >= 1 && month <= 12) {
            // 使用SQL的DATE_FORMAT函数提取月份（适用于MySQL）
            queryWrapper.apply("DATE_FORMAT(release_date, '%m') = {0}",
                    String.format("%02d", month)); // 确保月份是两位数（如9月→"09"）
        }
            QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
            employeeQueryWrapper.lambda().like(Employee::getEmployeeName, username);

            // 假设你有EmployeeService，可以通过它查询员工
            List<Employee> employees = employeeService.list(employeeQueryWrapper);

            // 如果查询到员工，获取他们的ID并作为条件
            if(employees != null && !employees.isEmpty()){
                List<String> employeeIds = new ArrayList<>();
                for (Employee employee : employees) {
                    Integer employeeId = employee.getEmployeeId();
                    employeeIds.add(String.valueOf(employeeId));
                }

                queryWrapper.lambda().eq(SalaryPaymentRecords::getIssuanceStatus,"已发放").in(SalaryPaymentRecords::getEmp,employeeIds);
            } else {
                // 如果没有查询到员工，可以直接返回空结果
                return R.success(new Page<>());
            }
        Page<SalaryPaymentRecords> page = new Page<>(current, size);
        salaryPaymentRecordsService.page(page, queryWrapper);
        return R.success(page);
    }

    @GetMapping("/list")
    public R<List<SalaryPaymentRecords>> page(
    ){
        QueryWrapper<SalaryPaymentRecords> queryWrapper = new QueryWrapper<>();

        List<SalaryPaymentRecords> salaryStructures = salaryPaymentRecordsService.list(queryWrapper);
        return R.success(salaryStructures);
    }
    @PostMapping("/saveBatch")
    public R saveBatchSalaryData(@RequestBody List<SalaryPaymentRecords> tableData,
                                 @RequestAttribute("username") String username) {
        // 验证数据是否为空
        if (tableData == null || tableData.isEmpty()) {
            return R.error("提交的数据不能为空");
        }

        // 获取当前时间
        Date currentTime = new Date();

        // 为每条记录设置创建人和当前时间
        for (SalaryPaymentRecords record : tableData) {
            // 设置创建人为当前登录用户
            record.setCreatedBy(username);

            // 设置发放时间为当前时间
            record.setReleaseDate(currentTime);
            record.setIssuanceStatus("已发放");


        }

        System.out.println("接收的薪资数据总数：" + tableData.size());

        // 调用Service层批量保存或更新到数据库
        boolean saveSuccess = salaryPaymentRecordsService.saveOrUpdateBatch(tableData);

        if (saveSuccess) {
            return R.success("批量保存成功");
        } else {
            return R.error("批量保存失败");
        }
    }
    @PutMapping("/updatelist")
    public R updatelist(@RequestBody List<SalaryPaymentRecords> records) {
        try {
            // 验证输入数据
            if (records == null || records.isEmpty()) {
                return R.error("修改的数据不能为空");
            }

            // 调用服务层进行批量修改
            boolean success = salaryPaymentRecordsService.updateBatchById(records);

            if (success) {
                return R.success("批量修改成功");
            } else {
                return R.error("批量修改失败");
            }
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return R.error("服务器异常，批量修改失败：" + e.getMessage());
        }
    }

    @PutMapping("/update")
    public R update(@RequestBody SalaryPaymentRecords record) {
        try {
            // 1. 验证必要参数
            if (record.getEmp() == null || record.getReleaseDate() == null) {
                return R.error("员工姓名和发放日期不能为空");
            }

            // 2. 根据员工姓名和发放日期查询对应记录
            QueryWrapper<SalaryPaymentRecords> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SalaryPaymentRecords::getEmp, record.getEmp())
                    .eq(SalaryPaymentRecords::getReleaseDate, record.getReleaseDate());

            SalaryPaymentRecords existingRecord = salaryPaymentRecordsService.getOne(queryWrapper);

            // 3. 如果找到记录则更新状态
            if (existingRecord != null) {
                existingRecord.setIssuanceStatus("已确认");
                // 如果需要，可以在这里更新修改时间
                // existingRecord.setUpdateTime(new Date());

                boolean success = salaryPaymentRecordsService.updateById(existingRecord);
                if (success) {
                    return R.success("状态已更新为已确认");
                } else {
                    return R.error("更新记录失败");
                }
            } else {
                return R.error("未找到对应的薪资记录");
            }
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return R.error("更新失败: " + e.getMessage());
        }
    }

    @GetMapping("/find")
    public R<List<SalaryPaymentRecords>> pages(
            @RequestParam(name="emp",required = false) String emp,
            @RequestParam(name="departmental",required = false) String departmental,
            @RequestParam(name="postsName",required = false) String postsName,
            @RequestParam(name="createdBy",required = false) String createdBy,
            // 新增年份和月份参数（非必填）
            @RequestParam(name="year",required = false) Integer year,
            @RequestParam(name="month",required = false) Integer month
    ){
        QueryWrapper<SalaryPaymentRecords> queryWrapper = new QueryWrapper<>();
        if(year != null) {
            // 使用SQL的DATE_FORMAT函数提取年份（适用于MySQL）
            queryWrapper.apply("DATE_FORMAT(release_date, '%Y') = {0}", year);
        }

        // 处理Date类型的月份查询（重点修改部分）
        if(month != null && month >= 1 && month <= 12) {
            // 使用SQL的DATE_FORMAT函数提取月份（适用于MySQL）
            queryWrapper.apply("DATE_FORMAT(release_date, '%m') = {0}",
                    String.format("%02d", month)); // 确保月份是两位数（如9月→"09"）
        }
        if(emp != null){
            QueryWrapper<Employee> employeeQueryWrapper = new QueryWrapper<>();
            employeeQueryWrapper.lambda().like(Employee::getEmployeeName, emp);

            // 假设你有EmployeeService，可以通过它查询员工
            List<Employee> employees = employeeService.list(employeeQueryWrapper);

            // 如果查询到员工，获取他们的ID并作为条件
            if(employees != null && !employees.isEmpty()){
                List<String> employeeIds = new ArrayList<>();
                for (Employee employee : employees) {
                    Integer employeeId = employee.getEmployeeId();
                    employeeIds.add(String.valueOf(employeeId));
                }
                queryWrapper.lambda().in(SalaryPaymentRecords::getEmp, employeeIds);
            } else {
                // 如果没有查询到员工，可以直接返回空结果
                return R.success();
            }
        }
        if(departmental != null){
            queryWrapper.lambda().like(SalaryPaymentRecords::getDepartmental,departmental);
        }
        if(postsName != null){
            queryWrapper.lambda().like(SalaryPaymentRecords::getPostsname,postsName);
        }
        if(createdBy != null){
            queryWrapper.lambda().like(SalaryPaymentRecords::getCreatedBy,createdBy);
        }

        queryWrapper.orderByDesc("records_id");

        // 调用Service查询全部符合条件的数据（不带分页）
        List<SalaryPaymentRecords> records = salaryPaymentRecordsService.list(queryWrapper);

        return R.success(records);

    }

}
